package com.hwatsang.action;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.hwatsang.model.User;
import com.hwatsang.service.SmsAuthCodeService;
import com.hwatsang.service.UserService;
import com.hwatsang.view.UserModel;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport implements ServletResponseAware {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserAction.class);
	
	private static final long serialVersionUID = 1L;
	
	private final String FAIL_CODE = "-1";
	private final String FAIL_NEED_AUTH = "-101";
	private final String SUCCESS_CODE = "1";	
	private final String COOKIE_LOGIN_KEY = "login_key";
	
	private String authCode;
	private UserModel user;			
	private String dataError;	
	private HttpServletResponse response;
	
	private String resultCode;
	private String message;
	
	@Autowired
	private UserService userService;
	@Autowired
	private SmsAuthCodeService smsAuthCodeService;
			
	public String showLogin() {
		return "showLogin";
	}
	
	public String showFindPassword() {
		return "showFindPass";
	}
	
	public String showRegister() {
		return "showRegister";
	}
	
	public String register() {
		LOGGER.debug("Got a save user request! User mobile number is {}.", user.getMobilePhone());
		
		String mobilePhone = user.getMobilePhone();
		if(userService.getUserByMobilePhone(mobilePhone) != null) {
			resultCode = FAIL_CODE;
			message = "手机" + user.getMobilePhone() + "已经被注册！";
			return "regResult";
		}
		
		User userBean = new User();		
		BeanUtils.copyProperties(user, userBean);		
		
		String userId = userService.createNewUser(userBean);
		smsAuthCodeService.generateAndSendAuthCodeForUser(userId, mobilePhone);		
		user.setStringId(userId);
		
		message = null;
		resultCode = SUCCESS_CODE;
		return "regResult";
	}
	
	public String authSms() {
		String userId = user.getStringId();
		User userBean = userService.getUser(userId);
		if(userBean == null || userBean.getSmsAuthenticated() == 1) {
			resultCode = FAIL_CODE; 
			message = "无效的验证请求，手机号码已被验证过！";
			return "authResult";
		}
		
		String code = smsAuthCodeService.getAuthCodeByUser(userId);		
		if(StringUtils.equals(authCode, code)) {
			userService.updateUserToAuthenticated(userId);
			String loginKey = userService.generateNewLoginKeyAndStore(userId);
			response.addCookie(new Cookie(COOKIE_LOGIN_KEY, loginKey));
			message = null;
			resultCode = SUCCESS_CODE;			
			user.setName(userBean.getName());
			user.setGender(userBean.getGender());
			
			return "authResult";
		} else {
			resultCode = FAIL_CODE;
			message = "您输入的短信验证码有误，请重新输入！";
			return "authResult";
		}
	}
	
	public String login() {
		String inputPassword = user.getPassword();	
		User userBean = userService.getUserByMobilePhone(user.getMobilePhone());
		
		if(userBean == null || StringUtils.isBlank(inputPassword)) {
			resultCode = FAIL_CODE;
			message = "手机号码或登录密码错误，请重试";
			return "loginResult";
		}
		
		String userId = String.valueOf(userBean.getId());
		if (userBean.getSmsAuthenticated() == 0) {
			smsAuthCodeService.generateAndSendAuthCodeForUser(userId, userBean.getMobilePhone());
			resultCode = FAIL_NEED_AUTH;			
			message = "您的手机号码尚未验证，请先验证手机号码方可正常登陆。";
			user.setId(userBean.getId());			
			
			return "loginResult";
		} else {
			String correctPassword = userBean.getPassword();
			
			if(StringUtils.equals(correctPassword, inputPassword)) {
				// Login success
				userService.updateLastLogin(userId, new Date());
				String loginKey = userService.generateNewLoginKeyAndStore(userId);								
				response.addCookie(new Cookie(COOKIE_LOGIN_KEY, loginKey));
				user.setName(userBean.getName());
				user.setGender(userBean.getGender());
				resultCode = SUCCESS_CODE;
				
				return "loginResult";
			} else {
				resultCode = FAIL_CODE;
				message = "手机号码或登录密码错误，请重试";
				return "loginResult";
			}
		}
	}
	
	public String forgetPassword() {
		String mobilePhone = user.getMobilePhone();
		User userBean = userService.getUserByMobilePhone(mobilePhone);
		if(userBean == null) {
			resultCode = FAIL_CODE;
			message = "该手机号码不存在，请确认后重新输入";
			return "findPassResult";
		} else {
			//generate new password and update DB
			userService.generateNewPasswordForUser(mobilePhone);
			resultCode = SUCCESS_CODE;
			message = "请输入您通过手机" + mobilePhone + "收到的新密码";
			
			return "findPassResult";
		}
		
	}

	public UserModel getUser() {
		return user;
	}

	public void setUser(UserModel user) {
		this.user = user;
	}

	public void setAuthCode(String authCode) {
		this.authCode = authCode;
	}

	public String getDataError() {
		return dataError;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;		
	}

	public String getResultCode() {
		return resultCode;
	}

	public String getMessage() {
		return message;
	}
}
